﻿import QtQuick 2.5

Item {
    id: delegate
    width: imgWidth
    height: imgHeight
    clip: true
    antialiasing: true

    property alias rotation: rotation
    property alias img: name
    property alias rectHighlight: rectHighlight
    property int myIndex: -1
    property bool hasValue: false


    transform: Rotation{
        id: rotation
        origin.x: Math.floor(delegate.width/2)
        origin.y: Math.floor(delegate.height/2)
        axis.x: 0
        axis.y: 0
        axis.z: 1
        angle: 0
    }

    Rectangle{
        id: rectHighlight
        anchors.fill: parent
        color: "yellow"
        opacity: 0.3
    }

    Image {
        id: name
        x: -Math.floor(myIndex%type) * imgWidth
        y: -Math.floor(myIndex/type) * imgHeight
        source: imgSource == undefined ? "" : imgSource
        opacity: 0
        mipmap: true
    }

//    Text {
//        id: txt
//        anchors.centerIn: parent
//        text: hasValue
//        font.pixelSize: 40
//    }

    MouseArea{
        id: mouse
        anchors.fill: parent
        property real lastX: 0
        property real lastY: 0

        onPressed: {
            if(myIndex == -1) return

            currentDrag = myIndex
            name.opacity = 0
            items[myIndex].mouse.enabled = false
            items[myIndex].visible = true
            items[myIndex].z = 1

            lastX = mouseX
            lastY = mouseY

            startX = items[myIndex].x
            startY = items[myIndex].y

            lastIndex = index
        }

        onReleased: {
            items[myIndex].mouse.enabled = true
            items[myIndex].z = 0

            var result = calcEnd(items[myIndex].x + items[myIndex].width/2,items[myIndex].y + items[myIndex].height/2)

            hasValue = !result

            if(result == false){
                items[myIndex].visible = false
                name.opacity = 1
            }
            else{
                if(myIndex!=-1){
                    myIndex = -1
                }
            }
        }

        onPositionChanged: {
            if(myIndex == -1) return

            items[myIndex].x += mouseX - lastX
            items[myIndex].y += mouseY - lastY

            lastX = mouseX
            lastY = mouseY

            calcCenter(items[myIndex].x + items[myIndex].width/2,items[myIndex].y + items[myIndex].height/2)
        }

    }
}
